package com.example.filepersistencetest

import android.annotation.SuppressLint
import android.content.ContentValues
import android.database.Cursor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.filepersistencetest.SQLiteUtil.MyDatabaseHelper
import kotlinx.android.synthetic.main.activity_sqlactivity.*

class SQLActivity : AppCompatActivity() {
    @SuppressLint("Range")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sqlactivity)

        val dbHelper = MyDatabaseHelper(this,"BookStore.db",2)
        
        btnCreateSQLite.setOnClickListener{
            dbHelper.writableDatabase
        }
        
        btnAddData.setOnClickListener{
            val db = dbHelper.writableDatabase
            val value1 = ContentValues().apply { 
                //组装数据
                put("name","The Da Vinci Code")
                put("author","Dan Brown")
                put("pages",454)
                put("price",16.96)
            }
            db.insert("Book",null,value1)
            val value2 = ContentValues().apply {
                //组装数据
                put("name","The Lost Symbol")
                put("author","Dan Brown")
                put("pages",510)
                put("price",19.95)
            }
            db.insert("Book",null,value2)
        }
        
        btnUpdateData.setOnClickListener {
            val db = dbHelper.writableDatabase
            val values = ContentValues()
            values.put("price",10.99)
            db.update("Book",values,"name = ?", arrayOf("The Da Vinci Code"))
        }
        
        btnDeleteData.setOnClickListener {
            val db = dbHelper.writableDatabase
            db.delete("Book","pages > ?", arrayOf("500"))
        }
        
        btnQuery.setOnClickListener {
            val db = dbHelper.writableDatabase
            val cursor = db.query("Book",null,null,null,null,null,null)
            if(cursor.moveToFirst())
            {

                do{
                    //
                    val name = cursor.getString(cursor.getColumnIndex("name"))
                    val author = cursor.getString(cursor.getColumnIndex("author"))
                    val pages = cursor.getInt(cursor.getColumnIndex("pages"))
                    val price = cursor.getDouble(cursor.getColumnIndex("price"))
                    Log.d("MainActivity", "name is $name")
                    Log.d("MainActivity", "author is $author")
                    Log.d("MainActivity", "pages is $pages")
                    Log.d("MainActivity", "price is $price")
                }while (cursor.moveToNext())
            }
            cursor.close()
        }
        
        
    }
}